package day_2022_9_to_12.Day;

import java.util.HashMap;
import java.util.Map;

/**
 * @author haomin
 * @date 2022/10/04 20:55
 **/
public class Day33_2_Num166_FractionToDecimal {
    class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            StringBuffer sb = new StringBuffer();
            long a = numerator, b = denominator;
            if(a > 0 && b < 0 || a < 0 && b > 0) sb.append("-");
            a = Math.abs(a);
            b = Math.abs(b);
            sb.append(a/b);
            if(a % b == 0) return sb.toString();
            sb.append(".");
            Map<Long, Integer> map = new HashMap<>();
            while((a = (a % b) * 10) > 0 && !map.containsKey(a)){
                map.put(a, sb.length());
                sb.append(a/b);
            }
            if(a == 0) return sb.toString();
            return sb.insert(map.get(a).intValue(), "(").append(")").toString();
        }
    }
}